{% extends "members/base.html" %}

{% block title %}量表创建器{% endblock %}

{% block extra_css %}
<style>
    .creator-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 2rem;
        border-radius: 10px;
        margin-bottom: 2rem;
    }
    .step-indicator {
        display: flex;
        justify-content: center;
        margin-bottom: 2rem;
    }
    .step {
        display: flex;
        align-items: center;
        margin: 0 1rem;
    }
    .step-number {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #e9ecef;
        color: #6c757d;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        margin-right: 0.5rem;
    }
    .step.active .step-number {
        background-color: #007bff;
        color: white;
    }
    .step.completed .step-number {
        background-color: #28a745;
        color: white;
    }
    .content-section {
        display: none;
    }
    .content-section.active {
        display: block;
    }
    .question-item {
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 1rem;
        background: #f8f9fa;
    }
    .question-item:hover {
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    .option-input {
        margin-bottom: 0.5rem;
    }
    .drag-handle {
        cursor: move;
        color: #6c757d;
    }
    .preview-panel {
        background: white;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 1.5rem;
        max-height: 600px;
        overflow-y: auto;
    }
    
    /* 确保提示面板在中等屏幕上也保持在右侧 */
    @media (min-width: 992px) {
        .tips-panel-container {
            position: sticky;
            top: 20px;
        }
    }
    
    /* 在小屏幕上优化布局 */
    @media (max-width: 991px) {
        .tips-panel-container {
            margin-top: 2rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="creator-header">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h2 class="mb-1" id="page-title">创建新量表</h2>
                <p class="mb-0">设计您的心理测评量表，让专业更简单</p>
            </div>
            <div class="col-md-6">
                <div class="row">
                    <div class="col-md-6">
                        <button type="button" class="btn btn-light w-100" onclick="saveAsDraft()">
                            <i class="bi bi-cloud-upload me-2"></i>保存草稿
                        </button>
                    </div>
                    <div class="col-md-6">
                        <button type="button" class="btn btn-warning w-100" onclick="previewScale()">
                            <i class="bi bi-eye me-2"></i>预览
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 步骤指示器 -->
    <div class="step-indicator">
        <div class="step active" id="step-1">
            <div class="step-number">1</div>
            <span>基本信息</span>
        </div>
        <div class="step" id="step-2">
            <div class="step-number">2</div>
            <span>题目设计</span>
        </div>
        <div class="step" id="step-3">
            <div class="step-number">3</div>
            <span>发布设置</span>
        </div>
    </div>

    <!-- 第一步：基本信息 -->
    <div class="content-section active" id="section-1">
        <!-- 创建方式选择 -->
        <div class="row mb-4" id="creation-mode-section">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">选择创建方式</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card border-primary h-100" style="cursor: pointer;" onclick="selectCreationMode('blank')" id="blank-mode-card">
                                    <div class="card-body text-center">
                                        <i class="bi bi-file-earmark-plus text-primary" style="font-size: 3rem;"></i>
                                        <h6 class="mt-3">从空白开始</h6>
                                        <p class="text-muted small">创建全新的量表，从零开始设计题目</p>
                                        <div class="form-check d-flex justify-content-center">
                                            <input class="form-check-input" type="radio" name="creation-mode" id="mode-blank" value="blank" checked>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card border-secondary h-100" style="cursor: pointer;" onclick="selectCreationMode('copy')" id="copy-mode-card">
                                    <div class="card-body text-center">
                                        <i class="bi bi-files text-secondary" style="font-size: 3rem;"></i>
                                        <h6 class="mt-3">复制系统量表</h6>
                                        <p class="text-muted small">基于现有系统量表进行修改和定制</p>
                                        <div class="form-check d-flex justify-content-center">
                                            <input class="form-check-input" type="radio" name="creation-mode" id="mode-copy" value="copy">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 系统量表选择区域 -->
                        <div class="mt-4" id="system-scales-section" style="display: none;">
                            <h6>选择要复制的系统量表</h6>
                            <div class="row" id="system-scales-list">
                                <div class="col-12 text-center py-4">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">正在加载系统量表...</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-end mt-3">
                            <button type="button" class="btn btn-primary" onclick="confirmCreationMode()" id="confirm-mode-btn">确认并继续</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-5">
                <div class="card tips-panel-container">
                    <div class="card-header">
                        <h6 class="mb-0">创建提示</h6>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <h6><i class="bi bi-lightbulb me-2"></i>创建提示</h6>
                            <ul class="mb-0 small">
                                <li>选择合适的创建方式开始您的量表设计</li>
                                <li>从空白开始适合完全自定义的量表</li>
                                <li>复制系统量表可以快速基于现有模板创建</li>
                                <li>确保选择正确的量表分类和目标人群</li>
                            </ul>
                        </div>
                        
                        <div class="alert alert-warning mt-3">
                            <h6><i class="bi bi-exclamation-triangle me-2"></i>会员权限</h6>
                            <p class="mb-0 small">创建自定义量表需要专业会员或更高级别的会员资格。如果您是基础会员，请升级会员后再创建量表。</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 基本信息表单 -->
        <div class="row" id="basic-info-section" style="display: none;">
            <div class="col-xl-8 col-lg-7">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">量表基本信息</h5>
                    </div>
                    <div class="card-body">
                        <form id="basic-info-form">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="mb-3">
                                        <label for="scale-title" class="form-label">量表标题 <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="scale-title" placeholder="请输入量表标题" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="scale-category" class="form-label">量表分类 <span class="text-danger">*</span></label>
                                        <select class="form-select" id="scale-category" required>
                                            <option value="">请选择分类</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="scale-subtitle" class="form-label">副标题</label>
                                <input type="text" class="form-control" id="scale-subtitle" placeholder="简短的副标题（可选）">
                            </div>
                            
                            <div class="mb-3">
                                <label for="scale-description" class="form-label">量表描述 <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="scale-description" rows="3" placeholder="请描述量表的用途和目标" required></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="scale-instruction" class="form-label">测试说明</label>
                                <textarea class="form-control" id="scale-instruction" rows="4" placeholder="向测试者说明如何完成这个量表"></textarea>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="scale-author" class="form-label">作者</label>
                                        <input type="text" class="form-control" id="scale-author" placeholder="量表作者">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="scale-version" class="form-label">版本</label>
                                        <input type="text" class="form-control" id="scale-version" value="1.0" placeholder="版本号">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="estimated-time" class="form-label">预估时间（分钟）</label>
                                        <input type="number" class="form-control" id="estimated-time" placeholder="预估完成时间" min="1" max="120">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="copyright-info" class="form-label">版权信息</label>
                                <textarea class="form-control" id="copyright-info" rows="2" placeholder="版权声明或引用信息"></textarea>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-5">
                <div class="card tips-panel-container">
                    <div class="card-header">
                        <h6 class="mb-0">填写提示</h6>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <h6><i class="bi bi-lightbulb me-2"></i>填写提示</h6>
                            <ul class="mb-0 small">
                                <li>标题要简洁明了，能准确反映量表用途</li>
                                <li>描述要详细说明量表的目标和适用人群</li>
                                <li>测试说明要清晰，帮助测试者理解如何作答</li>
                                <li>预估时间有助于测试者安排时间</li>
                            </ul>
                        </div>
                        
                        <div class="alert alert-success mt-3">
                            <h6><i class="bi bi-check-circle me-2"></i>权限已开通</h6>
                            <p class="mb-0 small">您已具备创建自定义量表的权限，可以开始设计您的专属量表。</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 基本信息表单的下一步按钮 -->
        <div class="text-end mt-4" id="basic-info-next-btn" style="display: none;">
            <button type="button" class="btn btn-primary" onclick="nextStep(2)">下一步：题目设计</button>
        </div>
    </div>

    <!-- 第二步：题目设计 -->
    <div class="content-section" id="section-2">
        <div class="row">
            <div class="col-xl-8 col-lg-7">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">题目列表</h5>
                        <button type="button" class="btn btn-primary btn-sm" onclick="addQuestion()">
                            <i class="bi bi-plus-circle me-1"></i>添加题目
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="questions-container">
                            <div class="text-center py-4 text-muted">
                                <i class="bi bi-journal-text" style="font-size: 3rem; opacity: 0.5;"></i>
                                <p class="mt-2">还没有题目，点击"添加题目"开始创建</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-5">
                <div class="preview-panel tips-panel-container">
                    <h6 class="mb-3"><i class="bi bi-eye me-2"></i>实时预览</h6>
                    <div id="preview-container">
                        <p class="text-muted">添加题目后可在此预览</p>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="d-flex justify-content-between mt-4">
            <button type="button" class="btn btn-outline-secondary" onclick="prevStep(1)">上一步</button>
            <button type="button" class="btn btn-primary" onclick="nextStep(3)">下一步：发布设置</button>
        </div>
    </div>

    <!-- 第三步：发布设置 -->
    <div class="content-section" id="section-3">
        <div class="row">
            <div class="col-xl-8 col-lg-7">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">发布设置</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">可见性</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="visibility" id="public" value="true" checked>
                                        <label class="form-check-label" for="public">
                                            <strong>公开</strong>
                                            <div class="small text-muted">所有用户都可以看到并使用</div>
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="visibility" id="private" value="false">
                                        <label class="form-check-label" for="private">
                                            <strong>私有</strong>
                                            <div class="small text-muted">仅自己可见</div>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">收费设置</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="pricing" id="free" value="true" checked>
                                        <label class="form-check-label" for="free">
                                            <strong>免费</strong>
                                            <div class="small text-muted">用户可免费使用</div>
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="pricing" id="paid" value="false">
                                        <label class="form-check-label" for="paid">
                                            <strong>付费</strong>
                                            <div class="small text-muted">用户需付费使用</div>
                                        </label>
                                    </div>
                                </div>
                                <div class="mb-3" id="price-setting" style="display: none;">
                                    <label for="scale-price" class="form-label">价格（元）</label>
                                    <input type="number" class="form-control" id="scale-price" placeholder="请输入价格" min="0" step="0.01">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card mt-4">
                    <div class="card-header">
                        <h5 class="mb-0">量表预览</h5>
                    </div>
                    <div class="card-body">
                        <div id="final-preview">
                            <p class="text-muted">正在生成预览...</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-5">
                <div class="card tips-panel-container">
                    <div class="card-header">
                        <h6 class="mb-0">发布检查</h6>
                    </div>
                    <div class="card-body">
                        <div id="publish-checklist">
                            <div class="check-item" id="check-title">
                                <i class="bi bi-circle text-muted me-2"></i>填写标题
                            </div>
                            <div class="check-item" id="check-description">
                                <i class="bi bi-circle text-muted me-2"></i>填写描述
                            </div>
                            <div class="check-item" id="check-category">
                                <i class="bi bi-circle text-muted me-2"></i>选择分类
                            </div>
                            <div class="check-item" id="check-questions">
                                <i class="bi bi-circle text-muted me-2"></i>添加题目
                            </div>
                        </div>
                        
                        <hr>
                        
                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-success" id="publish-btn" onclick="publishScale()" disabled>
                                <i class="bi bi-upload me-2"></i>发布量表
                            </button>
                            <button type="button" class="btn btn-outline-primary" onclick="saveAsDraft()">
                                <i class="bi bi-cloud-upload me-2"></i>保存为草稿
                            </button>
                        </div>
                        
                        <div class="alert alert-info mt-3">
                            <h6><i class="bi bi-info-circle me-2"></i>发布说明</h6>
                            <ul class="mb-0 small">
                                <li>发布后的量表将对所有用户可见</li>
                                <li>草稿状态可以随时修改和完善</li>
                                <li>发布前请仔细检查所有信息</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="d-flex justify-content-between mt-4">
            <button type="button" class="btn btn-outline-secondary" onclick="prevStep(2)">上一步</button>
        </div>
    </div>
</div>

<!-- 题目编辑模态框 -->
<div class="modal fade" id="questionModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="questionModalTitle">添加题目</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="question-form">
                    <div class="mb-3">
                        <label for="question-text" class="form-label">题目内容 <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="question-text" rows="3" placeholder="请输入题目内容" required></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="question-type" class="form-label">题目类型 <span class="text-danger">*</span></label>
                                <select class="form-select" id="question-type" required onchange="handleQuestionTypeChange()">
                                    <option value="">请选择类型</option>
                                    <option value="single">单选题</option>
                                    <option value="multiple">多选题</option>
                                    <option value="scale">量表题（评分）</option>
                                    <option value="text">文本题</option>
                                    <option value="boolean">是/否题</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <div class="form-check mt-4">
                                    <input class="form-check-input" type="checkbox" id="question-required" checked>
                                    <label class="form-check-label" for="question-required">
                                        必答题目
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div id="options-section" style="display: none;">
                        <label class="form-label">选项设置</label>
                        <div id="options-container"></div>
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="addOption()">
                            <i class="bi bi-plus me-1"></i>添加选项
                        </button>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveQuestion()">保存题目</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentStep = 1;
let currentScaleId = null;
let questions = [];
let currentQuestionIndex = -1;
let categories = [];

// 页面加载
document.addEventListener('DOMContentLoaded', function() {
    loadCategories();
    
    // 检查是否是编辑模式
    const urlParams = new URLSearchParams(window.location.search);
    const scaleId = urlParams.get('id');
    if (scaleId) {
        loadScaleForEdit(scaleId);
    }
    
    // 绑定事件
    document.querySelectorAll('input[name="pricing"]').forEach(radio => {
        radio.addEventListener('change', function() {
            const priceSettings = document.getElementById('price-setting');
            if (this.value === 'false') {
                priceSettings.style.display = 'block';
            } else {
                priceSettings.style.display = 'none';
            }
        });
    });
    
    // 表单验证
    document.getElementById('scale-title').addEventListener('input', validateForm);
    document.getElementById('scale-description').addEventListener('input', validateForm);
    document.getElementById('scale-category').addEventListener('change', validateForm);
});

// 加载分类
function loadCategories() {
    apiRequest('/api/scales/categories')
        .then(response => {
            if (response.success) {
                categories = response.data.categories;
                const select = document.getElementById('scale-category');
                select.innerHTML = '<option value="">请选择分类</option>';
                categories.forEach(category => {
                    select.innerHTML += `<option value="${category.id}">${category.name}</option>`;
                });
            }
        })
        .catch(error => {
            console.error('加载分类失败:', error);
        });
}

// 加载量表用于编辑
function loadScaleForEdit(scaleId) {
    currentScaleId = scaleId;
    document.getElementById('page-title').textContent = '编辑量表';
    
    // 获取编辑模式参数
    const urlParams = new URLSearchParams(window.location.search);
    const mode = urlParams.get('mode');
    
    // 编辑模式下直接显示基本信息表单，隐藏创建方式选择
    document.getElementById('creation-mode-section').style.display = 'none';
    document.getElementById('basic-info-section').style.display = 'block';
    document.getElementById('basic-info-next-btn').style.display = 'block';
    
    apiRequest(`/api/scales/${scaleId}/edit`)
        .then(response => {
            if (response.success) {
                const scale = response.data;
                
                // 检查量表状态，如果已发布且尝试编辑题目，则阻止
                if (scale.status === 'PUBLISHED' && mode === 'questions') {
                    alert('已发布的量表不能修改题目设计！');
                    window.location.href = `/members/scale-creator?id=${scaleId}&mode=basic`;
                    return;
                }
                
                // 填充基本信息
                document.getElementById('scale-title').value = scale.title || '';
                document.getElementById('scale-subtitle').value = scale.subtitle || '';
                document.getElementById('scale-description').value = scale.description || '';
                document.getElementById('scale-instruction').value = scale.instruction || '';
                document.getElementById('scale-category').value = scale.category_id || '';
                document.getElementById('scale-author').value = scale.author || '';
                document.getElementById('scale-version').value = scale.version || '1.0';
                document.getElementById('copyright-info').value = scale.copyright_info || '';
                
                // 设置可见性和收费
                if (scale.is_public === false) {
                    document.getElementById('private').checked = true;
                }
                if (scale.is_free === false) {
                    document.getElementById('paid').checked = true;
                    document.getElementById('price-setting').style.display = 'block';
                    document.getElementById('scale-price').value = scale.price || '';
                }
                
                // 加载题目
                loadQuestions(scaleId);
                
                // 根据模式参数决定显示哪个步骤
                if (mode === 'questions') {
                    // 直接跳转到题目设计步骤
                    nextStep(2);
                } else if (mode === 'basic') {
                    // 保持在基本信息步骤
                    currentStep = 1;
                }
                
                // 验证表单
                validateForm();
            }
        })
        .catch(error => {
            console.error('加载量表失败:', error);
            alert('加载量表失败，请稍后重试');
        });
}

// 加载题目
function loadQuestions(scaleId) {
    apiRequest(`/api/scales/${scaleId}/questions`)
        .then(response => {
            if (response.success) {
                questions = response.data.questions || [];
                renderQuestions();
                updatePreview();
            }
        })
        .catch(error => {
            console.error('加载题目失败:', error);
        });
}

// 步骤控制
function nextStep(step) {
    if (step === 2 && !validateBasicInfo()) {
        return;
    }
    
    if (step === 3) {
        generateFinalPreview();
    }
    
    // 隐藏当前步骤
    document.getElementById(`section-${currentStep}`).classList.remove('active');
    document.getElementById(`step-${currentStep}`).classList.remove('active');
    document.getElementById(`step-${currentStep}`).classList.add('completed');
    
    // 显示新步骤
    currentStep = step;
    document.getElementById(`section-${currentStep}`).classList.add('active');
    document.getElementById(`step-${currentStep}`).classList.add('active');
    
    validateForm();
}

function prevStep(step) {
    document.getElementById(`section-${currentStep}`).classList.remove('active');
    document.getElementById(`step-${currentStep}`).classList.remove('active');
    
    currentStep = step;
    document.getElementById(`section-${currentStep}`).classList.add('active');
    document.getElementById(`step-${currentStep}`).classList.add('active');
    document.getElementById(`step-${currentStep}`).classList.remove('completed');
}

// 验证基本信息
function validateBasicInfo() {
    const title = document.getElementById('scale-title').value.trim();
    const description = document.getElementById('scale-description').value.trim();
    const category = document.getElementById('scale-category').value;
    
    if (!title) {
        alert('请填写量表标题');
        return false;
    }
    if (!description) {
        alert('请填写量表描述');
        return false;
    }
    if (!category) {
        alert('请选择量表分类');
        return false;
    }
    
    return true;
}

// 验证表单
function validateForm() {
    const title = document.getElementById('scale-title').value.trim();
    const description = document.getElementById('scale-description').value.trim();
    const category = document.getElementById('scale-category').value;
    
    // 更新检查列表
    updateCheckItem('check-title', !!title);
    updateCheckItem('check-description', !!description);
    updateCheckItem('check-category', !!category);
    updateCheckItem('check-questions', questions.length > 0);
    
    // 检查是否可以发布
    const canPublish = title && description && category && questions.length > 0;
    document.getElementById('publish-btn').disabled = !canPublish;
}

function updateCheckItem(id, isValid) {
    const item = document.getElementById(id);
    const icon = item.querySelector('i');
    if (isValid) {
        icon.className = 'bi bi-check-circle-fill text-success me-2';
    } else {
        icon.className = 'bi bi-circle text-muted me-2';
    }
}

// 题目管理
function addQuestion() {
    currentQuestionIndex = -1;
    document.getElementById('questionModalTitle').textContent = '添加题目';
    document.getElementById('question-form').reset();
    document.getElementById('question-required').checked = true;
    document.getElementById('options-section').style.display = 'none';
    document.getElementById('options-container').innerHTML = '';
    
    new bootstrap.Modal(document.getElementById('questionModal')).show();
}

function editQuestion(index) {
    currentQuestionIndex = index;
    const question = questions[index];
    
    document.getElementById('questionModalTitle').textContent = '编辑题目';
    document.getElementById('question-text').value = question.question_text;
    document.getElementById('question-type').value = question.question_type;
    document.getElementById('question-required').checked = question.is_required;
    
    // 处理选项
    if (question.options && question.options.length > 0) {
        document.getElementById('options-section').style.display = 'block';
        const container = document.getElementById('options-container');
        container.innerHTML = '';
        
        question.options.forEach((option, i) => {
            addOptionRow(option.option_text, option.option_value);
        });
    } else {
        document.getElementById('options-section').style.display = 'none';
    }
    
    handleQuestionTypeChange();
    
    new bootstrap.Modal(document.getElementById('questionModal')).show();
}

function deleteQuestion(index) {
    if (confirm('确定要删除这个题目吗？')) {
        questions.splice(index, 1);
        renderQuestions();
        updatePreview();
        validateForm();
    }
}

function handleQuestionTypeChange() {
    const type = document.getElementById('question-type').value;
    const optionsSection = document.getElementById('options-section');
    
    if (type === 'single' || type === 'multiple' || type === 'scale') {
        optionsSection.style.display = 'block';
        
        // 为量表题预设选项
        if (type === 'scale') {
            const container = document.getElementById('options-container');
            if (container.children.length === 0) {
                addOptionRow('非常不同意', 1);
                addOptionRow('不同意', 2);
                addOptionRow('中性', 3);
                addOptionRow('同意', 4);
                addOptionRow('非常同意', 5);
            }
        }
    } else {
        optionsSection.style.display = 'none';
    }
}

function addOption() {
    addOptionRow('', '');
}

function addOptionRow(text = '', value = '') {
    const container = document.getElementById('options-container');
    const index = container.children.length;
    
    const optionDiv = document.createElement('div');
    optionDiv.className = 'option-input d-flex align-items-center mb-2';
    optionDiv.innerHTML = `
        <span class="me-2">${String.fromCharCode(65 + index)}.</span>
        <input type="text" class="form-control me-2" placeholder="选项内容" value="${text}">
        <input type="number" class="form-control me-2" style="width: 100px;" placeholder="分值" value="${value}">
        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeOption(this)">
            <i class="bi bi-trash"></i>
        </button>
    `;
    
    container.appendChild(optionDiv);
}

function removeOption(btn) {
    btn.parentElement.remove();
    // 重新编号
    const container = document.getElementById('options-container');
    Array.from(container.children).forEach((div, index) => {
        div.querySelector('span').textContent = String.fromCharCode(65 + index) + '.';
    });
}

function saveQuestion() {
    const questionText = document.getElementById('question-text').value.trim();
    const questionType = document.getElementById('question-type').value;
    const isRequired = document.getElementById('question-required').checked;
    
    if (!questionText || !questionType) {
        alert('请填写完整的题目信息');
        return;
    }
    
    // 收集选项
    const options = [];
    const optionInputs = document.querySelectorAll('#options-container .option-input');
    optionInputs.forEach((div, index) => {
        const text = div.querySelector('input[type="text"]').value.trim();
        const value = div.querySelector('input[type="number"]').value;
        
        if (text) {
            options.push({
                option_key: String.fromCharCode(65 + index),
                option_text: text,
                option_value: parseInt(value) || (index + 1),
                sort_order: index + 1
            });
        }
    });
    
    // 检查选择题是否有选项
    if ((questionType === 'single' || questionType === 'multiple' || questionType === 'scale') && options.length === 0) {
        alert('请至少添加一个选项');
        return;
    }
    
    const question = {
        question_text: questionText,
        question_type: questionType,
        is_required: isRequired,
        options: options
    };
    
    if (currentQuestionIndex >= 0) {
        // 编辑模式
        questions[currentQuestionIndex] = question;
    } else {
        // 添加模式
        questions.push(question);
    }
    
    renderQuestions();
    updatePreview();
    validateForm();
    
    bootstrap.Modal.getInstance(document.getElementById('questionModal')).hide();
}

// 渲染题目列表
function renderQuestions() {
    const container = document.getElementById('questions-container');
    
    if (questions.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="bi bi-journal-text" style="font-size: 3rem; opacity: 0.5;"></i>
                <p class="mt-2">还没有题目，点击"添加题目"开始创建</p>
            </div>
        `;
        return;
    }
    
    let html = '';
    questions.forEach((question, index) => {
        html += `
            <div class="question-item">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <h6 class="mb-0">题目 ${index + 1}</h6>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-primary" onclick="editQuestion(${index})">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button type="button" class="btn btn-outline-danger" onclick="deleteQuestion(${index})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
                
                <p class="mb-2">${question.question_text}</p>
                
                <div class="d-flex align-items-center text-muted small">
                    <span class="badge bg-secondary me-2">${getQuestionTypeText(question.question_type)}</span>
                    ${question.is_required ? '<span class="badge bg-warning me-2">必答</span>' : ''}
                    ${question.options ? `<span>${question.options.length} 个选项</span>` : ''}
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 更新预览
function updatePreview() {
    const container = document.getElementById('preview-container');
    
    if (questions.length === 0) {
        container.innerHTML = '<p class="text-muted">添加题目后可在此预览</p>';
        return;
    }
    
    let html = '';
    questions.forEach((question, index) => {
        html += `
            <div class="mb-4">
                <p><strong>${index + 1}. ${question.question_text}</strong></p>
        `;
        
        if (question.options && question.options.length > 0) {
            question.options.forEach(option => {
                if (question.question_type === 'single' || question.question_type === 'scale') {
                    html += `
                        <div class="form-check">
                            <input class="form-check-input" type="radio" disabled>
                            <label class="form-check-label">${option.option_text}</label>
                        </div>
                    `;
                } else if (question.question_type === 'multiple') {
                    html += `
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" disabled>
                            <label class="form-check-label">${option.option_text}</label>
                        </div>
                    `;
                }
            });
        } else if (question.question_type === 'text') {
            html += '<textarea class="form-control" rows="3" disabled placeholder="文本输入框"></textarea>';
        } else if (question.question_type === 'boolean') {
            html += `
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" disabled>
                    <label class="form-check-label">是</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" disabled>
                    <label class="form-check-label">否</label>
                </div>
            `;
        }
        
        html += '</div>';
    });
    
    container.innerHTML = html;
}

// 生成最终预览
function generateFinalPreview() {
    const title = document.getElementById('scale-title').value;
    const subtitle = document.getElementById('scale-subtitle').value;
    const description = document.getElementById('scale-description').value;
    const instruction = document.getElementById('scale-instruction').value;
    
    let html = `
        <div class="mb-4">
            <h4>${title}</h4>
            ${subtitle ? `<p class="text-muted">${subtitle}</p>` : ''}
            <p>${description}</p>
            ${instruction ? `<div class="alert alert-info"><strong>测试说明：</strong>${instruction}</div>` : ''}
        </div>
    `;
    
    html += '<div class="border-top pt-3">';
    questions.forEach((question, index) => {
        html += `
            <div class="mb-4">
                <p><strong>${index + 1}. ${question.question_text}</strong> ${question.is_required ? '<span class="text-danger">*</span>' : ''}</p>
        `;
        
        if (question.options && question.options.length > 0) {
            question.options.forEach(option => {
                if (question.question_type === 'single' || question.question_type === 'scale') {
                    html += `
                        <div class="form-check">
                            <input class="form-check-input" type="radio" disabled>
                            <label class="form-check-label">${option.option_text}</label>
                        </div>
                    `;
                } else if (question.question_type === 'multiple') {
                    html += `
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" disabled>
                            <label class="form-check-label">${option.option_text}</label>
                        </div>
                    `;
                }
            });
        } else if (question.question_type === 'text') {
            html += '<textarea class="form-control" rows="3" disabled placeholder="文本输入框"></textarea>';
        } else if (question.question_type === 'boolean') {
            html += `
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" disabled>
                    <label class="form-check-label">是</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" disabled>
                    <label class="form-check-label">否</label>
                </div>
            `;
        }
        
        html += '</div>';
    });
    html += '</div>';
    
    document.getElementById('final-preview').innerHTML = html;
}

// 保存和发布
function saveAsDraft() {
    if (!validateBasicInfo()) {
        return;
    }
    
    const scaleData = getScaleData();
    
    if (currentScaleId) {
        // 更新现有量表
        updateScale(scaleData, true); // 传递isDraft参数
    } else {
        // 创建新量表作为草稿
        createScale(scaleData, false, true); // shouldPublish=false, isDraft=true
    }
}

function publishScale() {
    if (!validateBasicInfo() || questions.length === 0) {
        alert('请完善量表信息和题目后再发布');
        return;
    }
    
    if (currentScaleId) {
        // 先保存题目，再发布量表
        saveAllQuestions()
            .then(() => {
                return apiRequest(`/api/scales/${currentScaleId}/publish`, {
                    method: 'POST'
                });
            })
            .then(response => {
                if (response.success) {
                    alert('量表发布成功！');
                    window.location.href = '/members/my-scales';
                } else {
                    // 处理会员权限相关错误
                    if (response.message && (response.message.includes('会员') || response.message.includes('权限'))) {
                        showMembershipError(response.message);
                    } else {
                        alert('发布失败: ' + response.message);
                    }
                }
            })
            .catch(error => {
                console.error('发布失败:', error);
                alert('发布失败，请稍后重试');
            });
    } else {
        // 先创建再发布
        const scaleData = getScaleData();
        createScale(scaleData, true);
    }
}

function getScaleData() {
    return {
        title: document.getElementById('scale-title').value.trim(),
        subtitle: document.getElementById('scale-subtitle').value.trim(),
        description: document.getElementById('scale-description').value.trim(),
        instruction: document.getElementById('scale-instruction').value.trim(),
        category_id: parseInt(document.getElementById('scale-category').value),
        author: document.getElementById('scale-author').value.trim(),
        version: document.getElementById('scale-version').value.trim() || '1.0',
        copyright_info: document.getElementById('copyright-info').value.trim(),
        is_public: document.querySelector('input[name="visibility"]:checked').value === 'true',
        is_free: document.querySelector('input[name="pricing"]:checked').value === 'true',
        price: parseFloat(document.getElementById('scale-price').value) || 0,
        estimated_time: parseInt(document.getElementById('estimated-time').value) || null
    };
}

function createScale(scaleData, shouldPublish = false, isDraft = false) {
    apiRequest('/api/scales/create', {
        method: 'POST',
        body: JSON.stringify(scaleData)
    })
    .then(response => {
        if (response.success) {
            currentScaleId = response.data.id;
            
            // 保存题目
            saveAllQuestions()
                .then(() => {
                    if (shouldPublish) {
                        // 直接发布，不再调用publishScale()以避免重复保存题目
                        return apiRequest(`/api/scales/${currentScaleId}/publish`, {
                            method: 'POST'
                        })
                        .then(publishResponse => {
                            if (publishResponse.success) {
                                alert('量表发布成功！');
                                window.location.href = '/members/my-scales';
                            } else {
                                // 处理会员权限相关错误
                                if (publishResponse.message && (publishResponse.message.includes('会员') || publishResponse.message.includes('权限'))) {
                                    showMembershipError(publishResponse.message);
                                } else {
                                    alert('发布失败: ' + publishResponse.message);
                                }
                            }
                        });
                    } else if (isDraft) {
                        alert('草稿保存成功！');
                        // 草稿模式下不跳转，继续编辑
                    } else {
                        alert('量表创建成功！');
                        window.location.href = '/members/my-scales';
                    }
                })
                .catch(error => {
                    console.error('保存题目失败:', error);
                    if (isDraft) {
                        alert('草稿保存成功，但保存题目失败，请手动添加题目');
                    } else {
                        alert('量表创建成功，但保存题目失败，请手动添加题目');
                    }
                });
        } else {
            // 处理会员权限相关错误
            if (response.message && (response.message.includes('会员') || response.message.includes('权限'))) {
                showMembershipError(response.message);
            } else {
                alert('创建失败: ' + response.message);
            }
        }
    })
    .catch(error => {
        console.error('创建量表失败:', error);
        alert('创建失败，请稍后重试');
    });
}

function showMembershipError(message) {
    const errorHtml = `
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <h6><i class="bi bi-exclamation-triangle me-2"></i>会员权限不足</h6>
            <p class="mb-2">${message}</p>
            <div class="d-flex gap-2">
                <a href="/members/membership" class="btn btn-primary btn-sm">升级会员</a>
                <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="alert">知道了</button>
            </div>
        </div>
    `;
    
    // 在基本信息表单顶部显示错误信息
    const basicInfoSection = document.getElementById('basic-info-section');
    if (basicInfoSection) {
        basicInfoSection.insertAdjacentHTML('afterbegin', errorHtml);
    } else {
        alert(message);
    }
}

function updateScale(scaleData, isDraft = false) {
    apiRequest(`/api/scales/${currentScaleId}/edit`, {
        method: 'PUT',
        body: JSON.stringify(scaleData)
    })
    .then(response => {
        if (response.success) {
            // 保存题目
            return saveAllQuestions()
                .then(() => {
                    if (isDraft) {
                        alert('草稿保存成功！');
                    } else {
                        alert('量表更新成功！');
                    }
                })
                .catch(error => {
                    console.error('保存题目失败:', error);
                    if (isDraft) {
                        alert('草稿保存成功，但保存题目失败，请手动添加题目');
                    } else {
                        alert('量表更新成功，但保存题目失败，请手动添加题目');
                    }
                });
        } else {
            alert('更新失败: ' + response.message);
        }
    })
    .catch(error => {
        console.error('更新量表失败:', error);
        alert('更新失败，请稍后重试');
    });
}

async function saveAllQuestions() {
    console.log(`开始保存题目，当前题目数量: ${questions.length}`);
    
    // 先删除现有题目
    try {
        const existingQuestions = await apiRequest(`/api/scales/${currentScaleId}/questions`, {
            method: 'GET'
        });
        
        if (existingQuestions.success && existingQuestions.data.questions) {
            console.log(`删除现有题目数量: ${existingQuestions.data.questions.length}`);
            // 按照题目ID逆序删除，避免序号重排序问题
            const sortedQuestions = existingQuestions.data.questions.sort((a, b) => b.id - a.id);
            for (const question of sortedQuestions) {
                await apiRequest(`/api/scales/${currentScaleId}/questions/${question.id}`, {
                    method: 'DELETE'
                });
            }
            // 增加等待时间确保删除操作完全提交
            await new Promise(resolve => setTimeout(resolve, 500));
            
            // 验证删除是否完成
            let retryCount = 0;
            while (retryCount < 3) {
                const checkResult = await apiRequest(`/api/scales/${currentScaleId}/questions`, {
                    method: 'GET'
                });
                if (checkResult.success && checkResult.data.questions.length === 0) {
                    console.log('确认所有题目已删除');
                    break;
                }
                console.log(`等待删除完成，剩余题目: ${checkResult.data.questions.length}`);
                await new Promise(resolve => setTimeout(resolve, 300));
                retryCount++;
            }
        }
    } catch (error) {
        console.warn('删除现有题目时出错:', error);
    }
    
    // 保存新题目，明确指定题目序号，并添加重试机制
    for (let i = 0; i < questions.length; i++) {
        let retryCount = 0;
        let success = false;
        
        while (retryCount < 3 && !success) {
            try {
                const questionData = {
                    ...questions[i],
                    question_number: i + 1  // 明确指定题目序号
                };
                console.log(`保存题目 ${i + 1} (尝试 ${retryCount + 1}):`, questionData.question_text.substring(0, 50));
                const result = await apiRequest(`/api/scales/${currentScaleId}/questions`, {
                    method: 'POST',
                    body: JSON.stringify(questionData)
                });
                console.log(`题目 ${i + 1} 保存成功，ID: ${result.data?.id}`);
                success = true;
            } catch (error) {
                console.error(`保存题目 ${i + 1} 失败 (尝试 ${retryCount + 1}):`, error);
                retryCount++;
                
                if (error.message && error.message.includes('Duplicate entry')) {
                    console.log('检测到重复键错误，等待更长时间后重试...');
                    await new Promise(resolve => setTimeout(resolve, 1000));
                } else {
                    await new Promise(resolve => setTimeout(resolve, 300));
                }
                
                if (retryCount >= 3) {
                    throw error;
                }
            }
        }
    }
    
    console.log(`题目保存完成，共保存 ${questions.length} 个题目`);
    
    // 保存完成后重新获取题目列表验证
    try {
        const finalQuestions = await apiRequest(`/api/scales/${currentScaleId}/questions`, {
            method: 'GET'
        });
        if (finalQuestions.success) {
            console.log(`验证：最终题目数量为 ${finalQuestions.data.questions.length}`);
        }
    } catch (error) {
        console.warn('验证题目数量时出错:', error);
    }
}

// 工具函数
function getQuestionTypeText(type) {
    const typeMap = {
        'single': '单选题',
        'multiple': '多选题',
        'scale': '量表题',
        'text': '文本题',
        'boolean': '是/否题'
    };
    return typeMap[type] || type;
}

function previewScale() {
    if (currentScaleId) {
        window.open(`/api/scales/${currentScaleId}/preview`, '_blank');
    } else {
        alert('请先保存量表后再预览');
    }
}

// 创建方式选择相关函数
let selectedSystemScale = null;

function selectCreationMode(mode) {
    // 更新单选按钮状态
    document.getElementById('mode-blank').checked = mode === 'blank';
    document.getElementById('mode-copy').checked = mode === 'copy';
    
    // 更新卡片样式
    const blankCard = document.getElementById('blank-mode-card');
    const copyCard = document.getElementById('copy-mode-card');
    
    if (mode === 'blank') {
        blankCard.className = 'card border-primary h-100';
        copyCard.className = 'card border-secondary h-100';
        document.getElementById('system-scales-section').style.display = 'none';
    } else {
        blankCard.className = 'card border-secondary h-100';
        copyCard.className = 'card border-primary h-100';
        document.getElementById('system-scales-section').style.display = 'block';
        loadSystemScales();
    }
}

function loadSystemScales() {
    const container = document.getElementById('system-scales-list');
    
    // 显示加载状态
    container.innerHTML = `
        <div class="col-12 text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2 text-muted">正在加载系统量表...</p>
        </div>
    `;
    
    // 获取系统量表列表
    apiRequest('/api/scales/system', {
        method: 'GET'
    })
    .then(response => {
        if (response.success && response.data) {
            renderSystemScales(response.data);
        } else {
            container.innerHTML = `
                <div class="col-12 text-center py-4">
                    <i class="bi bi-exclamation-triangle text-warning" style="font-size: 2rem;"></i>
                    <p class="mt-2 text-muted">暂无可用的系统量表</p>
                </div>
            `;
        }
    })
    .catch(error => {
        console.error('加载系统量表失败:', error);
        container.innerHTML = `
            <div class="col-12 text-center py-4">
                <i class="bi bi-exclamation-triangle text-danger" style="font-size: 2rem;"></i>
                <p class="mt-2 text-muted">加载失败，请稍后重试</p>
                <button class="btn btn-sm btn-outline-primary" onclick="loadSystemScales()">重新加载</button>
            </div>
        `;
    });
}

function renderSystemScales(scales) {
    const container = document.getElementById('system-scales-list');
    
    if (!scales || scales.length === 0) {
        container.innerHTML = `
            <div class="col-12 text-center py-4">
                <i class="bi bi-info-circle text-info" style="font-size: 2rem;"></i>
                <p class="mt-2 text-muted">暂无可用的系统量表</p>
            </div>
        `;
        return;
    }
    
    let html = '';
    scales.forEach(scale => {
        html += `
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card h-100 system-scale-card" style="cursor: pointer;" onclick="selectSystemScale(${scale.id})" id="scale-card-${scale.id}">
                    <div class="card-body">
                        <h6 class="card-title">${scale.title}</h6>
                        <p class="card-text text-muted small">${scale.description || '暂无描述'}</p>
                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-muted">
                                <i class="bi bi-question-circle"></i> ${scale.question_count || 0} 题
                            </small>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="system-scale" value="${scale.id}">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

function selectSystemScale(scaleId) {
    // 清除之前的选择
    document.querySelectorAll('.system-scale-card').forEach(card => {
        card.classList.remove('border-primary');
        card.classList.add('border-secondary');
    });
    
    // 选中当前量表
    const selectedCard = document.getElementById(`scale-card-${scaleId}`);
    selectedCard.classList.remove('border-secondary');
    selectedCard.classList.add('border-primary');
    
    // 更新单选按钮
    document.querySelector(`input[name="system-scale"][value="${scaleId}"]`).checked = true;
    
    selectedSystemScale = scaleId;
}

function confirmCreationMode() {
    const mode = document.querySelector('input[name="creation-mode"]:checked').value;
    
    if (mode === 'copy') {
        if (!selectedSystemScale) {
            alert('请选择要复制的系统量表');
            return;
        }
        
        // 复制系统量表
        copySystemScale(selectedSystemScale);
    } else {
        // 从空白开始，显示基本信息表单
        showBasicInfoForm();
    }
}

function copySystemScale(scaleId) {
    const confirmBtn = document.getElementById('confirm-mode-btn');
    const originalText = confirmBtn.textContent;
    
    confirmBtn.disabled = true;
    confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>复制中...';
    
    apiRequest(`/api/scales/copy/${scaleId}`, {
        method: 'POST',
        body: JSON.stringify({
            title: `复制的量表 (副本)`
        })
    })
    .then(response => {
        if (response.success) {
            alert('量表复制成功！正在跳转到我的量表界面...');
            // 跳转到我的量表界面
            window.location.href = '/members/my-scales';
        } else {
            alert('复制失败: ' + response.message);
            confirmBtn.disabled = false;
            confirmBtn.textContent = originalText;
        }
    })
    .catch(error => {
        console.error('复制量表失败:', error);
        alert('复制失败，请稍后重试');
        confirmBtn.disabled = false;
        confirmBtn.textContent = originalText;
    });
}

function showBasicInfoForm() {
    // 隐藏创建方式选择区域
    document.getElementById('creation-mode-section').style.display = 'none';
    // 显示基本信息表单
    document.getElementById('basic-info-section').style.display = 'block';
    // 显示下一步按钮
    document.getElementById('basic-info-next-btn').style.display = 'block';
}

</script>
{% endblock %}